import lvgl as lv
import time
import urequests
from machine import Pin
import config
import ujson
import os


def read_image(path):
    with open(path, 'rb') as f:
        icon_data = f.read()

    return lv.img_dsc_t({
        'data_size': len(icon_data),
        'data': icon_data
    })


def get_system_info():
    uname = os.uname()
    return {
        "name": config.DEVICE_NAME,
        "version": config.SYSTEM_VERSION,
        "mirror_flip": config.MIRROR_FLIP,
        "led": {
            "status": config.LED_STATUS,
            "rgb": config.LED_RGB
        },
        "server_api": config.SERVER_API,
        "secret_id": config.SECRET_ID,
        "secret_key": config.SECRET_KEY,
        "weather": {
            "loc": config.WEATHER_LOC,
            "city": config.WEATHER_CITY
        },
        "birthday_date": config.BIRTHDAY_DATE,
        "ip": config.IP,
        "ap": {"name": config.AP_NAME, "pwd": config.AP_PWD},
        "wifi": {"name": config.WIFI_NAME, "pwd": config.WIFI_PWD},
        "uname": {
            "sysname": uname.sysname,
            "nodename": uname.nodename,
            "release": uname.release,
            "version": uname.version,
            "machine": uname.machine
        }
    }


def get_weather(loc):
    try:
        res = urequests.get(url=f"{config.SERVER_API}/weather?loc={loc}",
                            headers={
                                "secret-id": config.SECRET_ID,
                                "secret-key": config.SECRET_KEY
                            })
        if res.status_code == 200:
            data = ujson.loads(res.content.decode())
            return data
    except Exception as err:
        print(err)
    return None


def is_birthday():
    now = time.localtime()
    m = now[1]
    d = now[2]
    if f"{m}-{d}" == config.BIRTHDAY_DATE:
        return True
    return False


class SwitchButton:
    continuous_period = 3000  # 连续按多少秒进入持续触发
    throttle_ms = 400  # 坑爹会触发多次，做一下节流

    def __init__(self, pin: Pin):

        self.__pin = pin

        self.__press_tick = 0
        self.__dbclick = 0

    def change(self):
        if self.__pin.value() == 1:
            self.__press_tick += 100
            self.__dbclick += 1

        print(self.__press_tick)
        if self.__dbclick >= 2 and self.__pin.value() == 0 and self.__press_tick > 0 and self.__press_tick <= 200:
            print("双击")
            self.__press_tick = 0
            self.__dbclick = 0

        if self.__press_tick > 200 and self.__press_tick <= 1000 and self.__pin.value() == 0:
            print("短按")
            self.__press_tick = 0

        if self.__press_tick > 3000 and self.__pin.value() == 1:
            print("长按 3000")
            self.__press_tick = 0
        if self.__pin.value() == 0:
            self.__press_tick = 0
            self.__dbclick = 0
